package com.portal.framework.common.lang;

import java.lang.reflect.Constructor;

public class ConstructorCaster<T> implements Caster<T> {
	private Class<T> clazz;

	public ConstructorCaster(Class<T> clazz) {
		this.clazz = clazz;
	}

	public T cast(Object o) {
		if (o == null) {
			return null;
		}

		Object[] os = null;
		if (o instanceof Object[]) {
			os = (Object[]) o;

			Constructor[] cons = clazz.getDeclaredConstructors();
			for (Constructor<T> c : cons) {
				if (os.length == c.getParameterTypes().length) {
					try {
						return c.newInstance(os);
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException(e);
					}
				}
			}
			// 表示只有一个
		} else {
			Constructor[] cons = clazz.getDeclaredConstructors();
			for (Constructor<T> c : cons) {
				if (1 == c.getParameterTypes().length) {
					try {
						return c.newInstance(o);
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException(e);
					}
				}
			}
		}

		return null;
	}

}
